<script setup>
import {onMounted, ref} from 'vue'
import * as echarts from 'echarts'

const chart = ref(null)
const getData = () => {

}
let websocket = null;
if ('WebSocket' in window) {
  // 创建WebSocket连接
  websocket = new WebSocket('ws://localhost:5151/ws/' + "110");
}
//连接发生错误
websocket.onerror = function (event) {
  console.log('连接错误');
};
//连接成功建立的回调方法
websocket.onopen = function (event) {
  console.log('WebSocket连接成功');
};

//接收到消息的回调方法
websocket.onmessage = function (event) {
  const data = JSON.parse(event.data)
  const echartInstance = echarts.init(chart.value)
  const option = {
    title: {
      text: '各地人口数',
      subtext: '2024年',
      subtextStyle: {
        color: '#999',
        fontSize: 14
      },
      textStyle: {
        color: 'yellow',
        fontSize: 18,
        fontWeight: 'bold'
      },
      left: '40%'
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: data.map(item => item.address),
      axisLabel: {
        color: '#2eeedd',
        fontSize: 14
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#2eeedd',
        fontSize: 14
      },
    },
    series: [{
      type: 'line',//line折线图
      data: data.map(item => item.count),
      itemStyle: {
        normal: {
          color: 'yellow', //改变折线点的颜色
          lineStyle: {
            color: 'rgb(5,190,250)' //改变折线颜色
          }
        }
      },
    },]
  }
  echartInstance.setOption(option)
}

//连接关闭的回调方法
websocket.onclose = function () {
  console.log("WebSocket连接关闭")
}

//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function () {
  websocket.close();
}
</script>

<template>
  <div ref="chart" style="width: 800px; height: 330px;"></div>
</template>

<style scoped>

</style>
